from django.shortcuts import render, redirect, HttpResponse
from .models import Department, UserInfo, PrettyNum
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from app16.utils.pagination import Pagination  # 导入分页组件


# Create your views here.
def home(request):
    return render(request, "app16/layout.html")


class DepartmentForm(forms.ModelForm):
    class Meta:
        model = Department
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


# 部门展示、删除
def depart_list(request):
    label = [form.label for form in DepartmentForm()]
    label.insert(0,"ID")
    label.append("操作")

    # 部门展示
    depart_obj = Pagination(request, queryset=Department.objects.all())
    content = {
        "label": label,
        "depart_list": depart_obj.page_queryset,
        "page_string": depart_obj.html(),
    }
    return render(request, "app16/department_list.html", content)


# 部门添加
def depart_add(request):
    if request.method == "GET":
        return render(request, "app16/department_add.html")

    title = request.POST.get("title")
    Department.objects.create(title=title)
    return redirect("/depart/list/")


# 部门删除
def depart_del(request):
    nid = request.GET.get("nid")
    Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")


# 部门修改
def depart_edit(request, nid):
    if request.method == "GET":
        edit = Department.objects.filter(id=nid).first()
        return render(request, "app16/depart_edit.html", {"edit": edit})

    # 获取用户更新信息
    # if request.method == 'POST':
    title = request.POST.get("title")
    Department.objects.filter(id=nid).update(title=title)
    return redirect("/depart/list/")

    # 用户
    # def user_add(request):
    # 添加用户
    if request.method == "GET":
        context = {
            "gender_choice": UserInfo.gender_choice,
            "depart_list": Department.objects.all(),
        }
        return render(request, "app16/user_add.html", context)
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("account")
    ctime = request.POST.get("ctime")
    gender = request.POST.get("gender")
    depart_id = request.POST.get("depart_id")
    print(user)

    # 添加到数据库
    UserInfo.objects.create(
        name=user,
        password=pwd,
        age=age,
        account=account,
        create_time=ctime,
        gender=gender,
        depart_id=depart_id,
    )
    return redirect("/user/list")


# ################################# ModelForm 示例 #################################
# from django import forms


# 根据 ModelForm 定义 UserForm 类
class UserForm(forms.ModelForm):
    name = forms.CharField(min_length=4, label="姓名")

    class Meta:
        model = UserInfo
        fields = [
            "name",
            "password",
            "age",
            "account",
            "create_time",
            "gender",
            "depart",
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


# 用户管理
def user_list(request):
    # 表格列头

    label = [form.label for form in UserForm()]
    label.insert(0, "ID")
    label.append("操作")

    user_list = UserInfo.objects.all()
    # for obj in user_list:
    #     print(
    #         obj.id,
    #         obj.name,
    #         obj.create_time.strftime("%Y-%m-%d"),  # 时间
    #         obj.gender,  # 性别
    #         obj.get_gender_display(),  # 性别，关联表，展示具体内容
    #     )
    #     print(
    #         obj.depart_id,
    #         obj.depart, # 不带 _id
    #     )

    # 获取数据并分页展示
    page_obj = Pagination(request, queryset=user_list)

    content = {
        "label": label,
        "user_list": page_obj.page_queryset,
        "page_string": page_obj.html(),
    }

    return render(request, "app16/user_list.html", content)


# 用户添加
def user_add(request):
    # 添加用户
    if request.method == "GET":
        form = UserForm()
        return render(request, "app16/user_add.html", {"form": form})

    # 用户POST提交数据，数据校验。
    form = UserForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect("/user/list/")
    # 校验失败（在页面上显示错误信息）
    return render(request, "app16/user_add.html", {"form": form})


# 编辑用户
def user_edit(request, nid):
    if request.method == "GET":
        row_obj = UserInfo.objects.filter(id=nid).first()
        form = UserForm(instance=row_obj)
        return render(request, "app16/user_edit.html", {"form": form})

    # 确定编辑对象
    row_obj = UserInfo.objects.filter(id=nid).first()
    form = UserForm(data=request.POST, instance=row_obj)
    # 验证
    if form.is_valid():
        form.save()
        return redirect("/user/list")
    return render(request, "app16/user_edit.html", {"form": form})


# 删除用户
def user_del(request, nid):
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list")


# from django.core.validators import RegexValidator


# 根据 ModelForm 重新定义 Pretty 类
class PrettyForm(forms.ModelForm):
    # 验证：方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[
            RegexValidator(r"^1[3-9]\d{9}$", "手机号格式错误"),
        ],
    )

    class Meta:
        model = PrettyNum
        # exclude = ['level']
        # fields = ["mobile", "price", "level", "status"]
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证：方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过，用户输入的值返回
        return txt_mobile


# 手机号列表
def pretty_list(request):
    # 靓号

    # 添加测试数据
    # for i in range(50):
    #     PrettyNum.objects.create(mobile="15730871471", price=10, level=1, status=1)

    # 表格列头
    label = [form.label for form in PrettyForm()]
    label.insert(0,"ID")
    label.append("操作")

    # 设置电话搜索
    mobile_dict = {}
    search_value = request.GET.get("search", "")
    if search_value:
        mobile_dict["mobile__contains"] = search_value

    # 查询 mobile 中包含 search_value 的数据
    queryset = PrettyNum.objects.filter(**mobile_dict)
    # queryset = PrettyNum.objects.filter(**mobile_dict).order_by("id") # 按 id 排序

    # 提取分页信息
    # Pagination(request, queryset, page_param="page", page_size=10, plus=5)
    page_obj = Pagination(request, queryset)

    # 传递到页面的数据
    content = {
        "label": label,
        "search_value": search_value,
        "queryset": page_obj.page_queryset,
        "page_string": page_obj.html(),
    }

    return render(request, "app16/pretty_list.html", content)


# 添加 pretty
def pretty_add(request):
    if request.method == "GET":
        form = PrettyForm()
        return render(request, "app16/pretty_add.html", {"form": form})
    # 用户POST提交数据，数据校验。
    form = PrettyForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect("/pretty/list/")
    # 校验失败（在页面上显示错误信息）
    return render(request, "app16/pretty_add.html", {"form": form})


# 定义靓号编辑类
class PrettyEditForm(forms.ModelForm):
    # 验证方式一：正则校验
    mobile = forms.CharField(
        # disabled=True,# 设置不可编辑
        label="手机号",
        validators=[
            RegexValidator(r"^1[3-9]\d{9}$", "手机号格式错误"),
        ],
    )

    class Meta:
        model = PrettyNum
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式二：手机重复？
    def clean_mobile(self):
        # 当前编辑的 id # print(self.instance.pk)
        # 获取当前手机号  # print(txt_mobile)
        txt_mobile = self.cleaned_data["mobile"]
        exists = (
            PrettyNum.objects.exclude(id=self.instance.pk)
            .filter(mobile=txt_mobile)
            .exists()
        )
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过，用户输入的值返回
        return txt_mobile


# 编辑靓号
def pretty_edit(request, nid):
    # 编辑靓号
    row_object = PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditForm(instance=row_object)
        return render(request, "app16/pretty_edit.html", {"form": form})

    form = PrettyEditForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")

    return render(request, "app16/pretty_edit.html", {"form": form})


# 删除靓号
def pretty_del(request, nid):
    # PrettyNum.objects.filter(id__gt=8).delete() #  __gt 大于；删除 id 大于 8 的数据
    PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
